import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'
import NavigationBar from '../../../components/navigationBar/index';
import { ShoppingCartpurchase, } from '../../../services/goods';
import { tempOrder, orderConfirm, orderPay, testPay } from '../../../services/order';

import './index.scss'
import { fullImgUrl, timeFormat } from '../../../utils/utils';
import Address from './img/icon_address.png';
import IconBorder from '../../../static/home/shopc.png';



export default class Index extends Component {
    config = {
        navigationBarTitleText: '结算中心',
        type: this.$router.params.id,
    }

    state = {
        list: [],
        pageObj: {
            page: 1,
            page_number: 10
        },
        tempOrderInfo: null,
        balance: Taro.getStorageSync('userInfo').balance,
        isMore: false,
        navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
        member_level: Taro.getStorageSync('userInfo').member_level,
        deliveryTime: '',
        startDeliveryTime: '',
        deliveryTimeShow: '',
    };
    componentWillMount() {
        let date = new Date();
        date.setDate(date.getDate() + 1);
        // 下午三点半以后，后天再发货
        if (date.getHours() > 15 || (date.getHours() === 15 && date.getMinutes() >= 30)) {
            date.setDate(date.getDate() + 1);
        }

        this.setState({
            startDeliveryTime: timeFormat(parseInt(date.getTime() / 1000, 10), 'yyyy-MM-dd'),
            deliveryTime: timeFormat(parseInt(date.getTime() / 1000, 10), 'yyyy-MM-dd'),
        })

        this.init();
    }
    componentDidShow() {
        console.log('componentDidShow');
        this.init()
    }
    init() {
        tempOrder({}).then(res => {
            this.setState({
                tempOrderInfo: res,
            });
        })
    }
    editAddress() {
        Taro.navigateTo({
            url: '/subPackageWork/pages/my-address/index?isEdit=1',
        });
    }
    dateChange(e) {
        this.setState({ dateChange: true })
        console.log('dateChange')

        if (e.detail.value == '2021-02-11' || e.detail.value == '2021-02-12' || e.detail.value == '2021-02-13') {
            Taro.showToast({
                title: '春节期间不发货,请重新选择发货时间!',
                icon: 'none'
            });
        } else {
            let temp = e.detail.value.split('-');
            console.log(temp)
            this.setState({
                deliveryTimeShow: `${temp[0]}年${temp[1]}月${temp[2]}日`
            })
        }
    }
    confirmOrder() {
        if (!this.state.deliveryTimeShow) {
            Taro.showToast({
                title: '请选择发货时间!',
                icon: 'none'
            });
            return;
        }
        if (!this.state.tempOrderInfo.address) {
            Taro.showToast({
                title: '请填写您的地址!',
                icon: 'none'
            });
            return;
        }
        // 订阅通知授权
        // 下单购买
        // 1. 新订单通知 dTw-cUo1WdE88M41QcPl6S6XFn0THY0lBkoUyOdjupQ
        // 2. 发货通知 m_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ
        // 3. 收货通知 1E1WejxNbO3B1mNUUMZIyr1XLccf76KKUDJFJBWd21g
        var deliveryTime = this.state.deliveryTimeShow;
        Taro.requestSubscribeMessage({
            tmplIds: ['dTw-cUo1WdE88M41QcPl6S6XFn0THY0lBkoUyOdjupQ', 'm_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ', '1E1WejxNbO3B1mNUUMZIyr1XLccf76KKUDJFJBWd21g'],
            complete: function (res) {
                orderConfirm({
                    delivery_time: deliveryTime,
                }).then(res => {
                    orderPay({
                        order_id: res.order_info_id,
                        pay_type: 3, // 连连支付
                        // pay_type: 1,
                        pay_platform: 1,
                    }).then(data => {
                        if (data == "此订单无需支付") {
                            Taro.redirectTo({
                                url: '/pages/my-order/index',
                            });
                        }
                        Taro.requestPayment({
                            ...JSON.parse(data.payload).metadata,
                            // ...data,
                            success() {
                                Taro.redirectTo({
                                    url: '/pages/my-order/index',
                                });
                            },
                            fail() {
                                Taro.redirectTo({
                                    url: '/pages/my-order/index',
                                });
                            },
                        });
                    });
                });
            },
        });
    }
    render() {
        const { tempOrderInfo, deliveryTime, deliveryTimeShow } = this.state;
        return tempOrderInfo ? (
            <View className='settlement' style={`margin-top: ${navigationBarHeight}`} >
                <NavigationBar text='结算中心' type="activity" />

                <View className="chunk">
                    <Image className="icon" src={Address}></Image>

                    <View className="content">
                        <View className="layout">
                            <View className="sett-title">{tempOrderInfo.address.province_name}{tempOrderInfo.address.city_name}</View>
                            <View className="sett-title">{tempOrderInfo.address.region_name}</View>
                        </View>
                        <View className="layout">
                            <View className="sett-title">{tempOrderInfo.address.receiver}</View>
                            <View className="sett-title">{tempOrderInfo.address.mobile}</View>
                            <View className="nextFont" onClick={this.editAddress}>选择地址 <text style={'font-size:30rpx;font-weight:900'}>&gt;</text>
                                {/* <Image className="next" src={Right}></Image> */}
                            </View>
                        </View>
                    </View>
                </View>
                <View className="main">
                    <View className="logo">
                        <Image className="icon" src={IconBorder}></Image>
                        <View className="text">中鹿岛</View>
                    </View>
                    {
                        tempOrderInfo.goods.map(res => (
                            <View className="center">
                                <View className="goodlsit-top">
                                    <Image className="images" src={fullImgUrl(res.sku.cover)}></Image>
                                    <View className="right">
                                        <View className="tittle">{res.sku.goods_name}</View>
                                        <View className="tittle_des">珍品品鉴券</View>
                                        <View className="layout">
                                            <View className="small">X{res.num}</View>
                                            <View className="money">￥ 0</View>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        ))
                    }

                    <View className="footer">
                        <View></View>
                        <View className="layout">
                            <View >小计</View>
                            <View className="last">￥{tempOrderInfo.paid_amount}</View>
                        </View>
                    </View>
                </View>
                <View className="chunk">
                    <View className="content1">
                        <View className="layout">
                            <View className="shop-free">运费</View>
                            <View className="shop-time">￥{tempOrderInfo.shopping_fee}</View>
                        </View>
                        <View className="layout">
                            <View className="shop-free">发货时间</View>
                            <Picker className="date-picker" value={deliveryTime} mode='date' start={startDeliveryTime} onChange={this.dateChange}>
                                <View className="wrap">
                                    {/* <View className="time-number"> */}
                                    <View className="time-number">
                                        {
                                            deliveryTimeShow ? (
                                                <View>{deliveryTimeShow}</View>

                                            ) : (
                                                <View>选择时间 <text style={'font-size:30rpx;font-weight:900'}>&gt;</text></View>
                                            )
                                        }</View>
                                </View>
                            </Picker>
                        </View>
                    </View>
                </View>
                <View className="goods-time">
                    <Text className='delivery-desc'>发货说明：</Text>
                    <Text className='delivery-desc'>我们将根据您选择的发货时间，每日安排现捕现捞，每日截单时间为15:30，如在当日15:30后下单，我们将顺延一天发货，发货后约24小时
                        顺丰冰鲜直达，请合理安排您的下单时间哦~
                    </Text>
                    <Text className='delivery-desc'>客服热线：4008-921-221</Text>
                </View>
                <View className="commonfooter">
                    <View style='display:flex;align-items: center;'>
                        <View className="bigmoneyFu">￥</View>
                        <View className="bigmoney" > {tempOrderInfo.paid_amount}</View>
                    </View>
                    <View className="wechart" onClick={this.confirmOrder}>立即兑换</View>
                </View>
            </View>
        ) : (
            <View></View>
        );
    }
}